﻿@model Round

@{
    ViewBag.Title = string.Format("Redigér {0}", "runde");
}

<div class="page-header">
    <h1><span class="glyphicon glyphicon-globe"></span> @ViewBag.Title</h1>
</div>

<div class="alert alert-info alert-dismissable">
    <p><b>BEMÆRK</b>: Du kan indberette en runde som værende 'privat'. Private runder tæller ikke på listerne, men medtages kun i statistikker. Runder med kun ét scorekort, som ikke er markeret som 'privat', fjernes automatisk løbende af systemet.</p>
</div>

@if (!ViewData.ModelState.IsValid)
{
    <div class="alert alert-danger alert-dismissable">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
        @Html.ValidationSummary("", new { @style = "color: #fff;" })
    </div>
}

@using (Html.BeginForm("Edit", "Round", FormMethod.Post, new { role = "form", @class = "form-horizontal" }))
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(x => x.CourseId)
    
    <div class="form-group">
        <label for="DateEntry" class="col-sm-2 col-lg-2 control-label">dato</label>
        <div class="col-sm-3">
            <div class="input-group">
                <span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span>
                <input type="text" id="DateEntry" name="DateEntry" class="form-control datepicker" required placeholder="dato" value="@Model.DateEntry.ToShortDateString()">
            </div>
        </div>
    </div>

    <div class="form-group">
        <label for="Cours" class="col-sm-2 col-lg-2 control-label">klub</label>
        <div class="col-sm-6">
            <div class="input-group">
                <span class="input-group-addon"><span class="glyphicon glyphicon-globe"></span></span>
                <input type="text" id="DummyCourseName" name="DummyCourseName" class="form-control" required placeholder="klub/bane" value="@Model.Course.Name" readonly>
            </div>
        </div>
    </div>

    <div class="form-group">
        <label for="EventId" class="col-sm-2 col-lg-2 control-label">event</label>
        <div class="col-sm-6">
            <div class="input-group">
                <span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span>
                @Html.DropDownListFor(m => m.EventId, new SelectList(ViewBag.Events, "Id", "NameForDropdown"), "Vælg eventuelt event..", new { @class = "form-control" })
            </div>
        </div>
    </div>

    <div class="form-group">
        <label for="IsPrivate" class="col-sm-2 col-lg-2 control-label">privat?</label>
        <div class="col-sm-6">
            @Html.CheckBoxFor(model => model.IsPrivate)
        </div>
    </div>

    <div class="form-group">
        <label for="create" class="col-sm-2 col-lg-2 control-label"></label>
        <div class="col-sm-4">
            <button type="submit" name="btnSubmit" class="btn btn-default" value="save">gem</button>
            &nbsp;
            <button type="submit" name="btnSubmit" class="btn btn-danger" value="delete">slet</button>
        </div>
    </div>
}

<hr>
<h3>scorekorts for runden</h3>
@Html.Partial("_RoundScore", Model)

<div class="form-group col-md-3">
    <div class="input-group">
        <span class="input-group-addon glyphicon glyphicon-user"></span>
        @Html.DropDownList("player", new SelectList(ViewBag.Players, "Id", "DisplayName", "Sex", new { }), "Vælg en spiller..", new { @class = "form-control" })
    </div>
</div>

<!-- Use ChildAction instead -->
<div class="form-group col-md-3">
    <div class="input-group">
        <span class="input-group">
            <span class="input-group-addon glyphicon glyphicon-flag"></span>
            @*@Html.DropDownList("tee", new SelectList(ViewBag.Tees, "Id", "DisplayName"), new { @class = "form-control" })*@
            <select id="tee" class="form-control">
                <option>Vælg spiller først</option>
            </select>
        </span>
    </div>
</div>

@*@Html.RenderAction("GetBySex", "Tee")*@

@* ActionLink this instead? Create(int playerId, int roundId, int teeId) *@
<div class="form-group col-md-1">
    <button class="btn btn-info ajaxAdd" data-roundid="@Model.Id">tilføj</button>
</div>

<div class="form-group col-md-4">
    <div class="input-group">
        <label for="CourseId">Mangler der et Tee sted?</label>
        @Html.ActionLink("opret ny tee", "CreateForCourse", "Tee", new { id = Model.CourseId }, new { @class = "btn btn-success" })
    </div>
</div>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title" id="myModalLabel">Score indberetning</h4>
            </div>
            <div id="modalbody" class="modal-body text-center">

            </div>
            <div class="modal-footer">
                <button type="button" class="hidden btn btn-primary ajaxPost">Opret</button>
                <button type="button" class="hidden btn btn-primary ajaxSave">Gem</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Luk</button>
            </div>
        </div>
    </div>
</div>
@section Scripts {
    @Scripts.Render("~/bundles/globalize")
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/Scripts/_thecup_editing.js")
<script>
    $(document).on("click", ".ajaxAdd", function (e) {
        // prevent post on buttonclick
        e.preventDefault();

        // which player was selected in DDL?
        var playerid = $("#player").val();
        var roundid = $(e.target).data("roundid");
        var teeid = $("#tee").val();
        
        if (playerid === "")
        {
            alertify.error("Vælg en spiller.")
            return;
        }
        if (teeid === undefined || teeid === "")
        {
            alertify.error("Vælg Tee.");
            return;
        }

        $.post("/Score/AddScorecard", { roundId: roundid, playerId: playerid, teeId: teeid }, function (data) {
            $("#modalbody").html(data);

            $("#myModal").on("show.bs.modal", function () {
                // calc pre-entered scores
                theCup.updateScore();
            });

            $("#myModal").on("shown.bs.modal", function () {
                var firstInput = $(".scoreVertical input:first").get(0);
                firstInput.focus();
                firstInput.select();
            });
            
            $(".ajaxPost").removeClass("hidden");
            
            $("#myModal").modal('show');
        });
    });

    $(".roundscore").on("click", ".ajaxEdit", function (e) {
        e.preventDefault();

        // fetch clicked id
        var scoreid = $(e.target).data("scoreid");

        $.get("/Score/Vertical", { id: scoreid }, function (data) {
            $("#modalbody").html(data);

            $("#myModal").on("show.bs.modal", function () {
                theCup.updateScore();
            });

            $("#myModal").on("shown.bs.modal", function () {
                $(".scoreVertical input:first").focus();
            });

            $(".ajaxSave").removeClass("hidden");

            $("#myModal").modal('show');
        });
    });

    // ajaxPost for creating
    $(".modal").on("click", ".ajaxPost", function (e) {
        e.preventDefault();
        
        var myForm = $("#scoreVert");
                
        $.ajax({
            url: "/Score/Create",
            type: "POST",
            data: myForm.serialize(),
            success: function (data) {
                $("#myModal").modal('hide');
                alertify.success("scorekort tilføjet!");
                $(".roundscore").prepend(data);
                // hide the button we clicked
                $(e.target).addClass("hidden");
            },
            error: function () {
                alertify.error("der opstod en fejl, prøv igen!", "fejl");
            }
        });
    });

    // ajaxSave for editing
    $(".modal").on("click", ".ajaxSave", function (e) {
        e.preventDefault();
                
        var myForm = $("#scoreVert");
        
        $.ajax({
            url: "/Score/Edit/",
            type: "POST",
            data: myForm.serialize(),
            success: function (data) {
                $("#myModal").modal('hide');
                var scoreid = $("#Id").val();
                // add sibling row data and remove current
                $("#score" + scoreid).after(data).remove();
                
                // new object, same id
                $("#score" + scoreid).fadeOut(500).fadeIn(500);

                // hide the button we clicked
                $(e.target).addClass("hidden");
                alertify.success("scorekort ændret!");
            },
            error: function () {
                alertify.error("der opstod en fejl, prøv igen!", "fejl");
            }
        });
                        
    });

    // don't forget to use delegate's on ajax created content :)
    $(".roundscore").on("click", ".ajaxDelete", function (e) {
        // prevent post on buttonclick
        e.preventDefault();

        // button clicked
        var btn = $(e.target);
        var id = btn.data("id");

        $.ajax({
            url: "/api/Score/" + id,
            type: "DELETE",
            success: function () {
                // remove row on success
                btn.parents("tr").remove();
                alertify.success("scorekort slettet");
            },
            error: function () {
                alertify.error("der opstod en fejl, prøv igen!", "fejl");
            }
        });
    });

    // Scorecard calculator
    $(".modal-body").on("input", "#scoreVert", function () {
        theCup.updateScore(this);
    });

    $("#player").on("change", function (e) {
        $.getJSON("/api/Tee/", { playerid: this.value, courseid: $("#CourseId").val() }, function (data) {
            // populate dropdown with tee's 
            var select = document.getElementById('tee');

            while (select.firstChild) {
                select.removeChild(select.firstChild);
            }
                        
            if (data.length === 0) {
                var option = document.createElement("option");
                option.value = "";
                option.text = "ingen tees";
                select.appendChild(option);
            }
            else {
                $.each(data, function (index, value) {
                    var option = document.createElement("option");
                    option.value = value.Id;
                    option.textContent = value.Name;
                    select.appendChild(option);
                });
            }
        });
    });

    $(".roundscore input").on("focus", function (item) {
        //console.log(item);
        item.select();
    });
</script>
}
